package service

import (
	"ollama-go/dto"
	"ollama-go/entity"
	"ollama-go/query"
	"ollama-go/vo"
	"time"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/sno"
	"gorm.io/gorm"
)

var tsTaskService *TsTaskService

type TsTaskService struct {
}

func NewTsTaskService() *TsTaskService {
	if tsTaskService == nil {
		tsTaskService = new(TsTaskService)
	}
	return tsTaskService
}

// 使用id获取数据
func (m TsTaskService) Get(id string) *vo.TsTaskVO {
	data := new(entity.TsTask)
	data.Id = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return nil
	}
	return sc.Copy[vo.TsTaskVO](data)
}

// 保存数据
func (m TsTaskService) Save(dto *dto.TsTaskDTO) error {
	data := sc.Copy[entity.TsTask](dto)
	data.Id = sno.GetString()
	data.UpdateTime = time.Now()
	err := sgorm.DB.Insert(data)
	return err
}

// 更新数据
func (m TsTaskService) UpdateById(dto *dto.TsTaskDTO) error {
	dbEntity := new(entity.TsTask)
	dbEntity.Id = dto.Id
	sgorm.DB.GetOne(dbEntity)
	sc.CopyTo(dto, dbEntity)
	dbEntity.UpdateTime = time.Now()
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m TsTaskService) DeleteById(id string) error {
	sgorm.DB.Tx(func(tx *gorm.DB) error {
		err := tx.Where("task_id = ?", id).Delete(entity.TsTaskStep{}).Error
		if err != nil {
			return err
		}
		err = tx.Where("id = ?", id).Delete(entity.TsTask{}).Error
		if err != nil {
			return err
		}
		return nil
	})
	err := sgorm.DB.DeleteById(entity.TsTask{}, id)
	return err
}

// 分页列表查询
func (m TsTaskService) QueryPage(query *query.TsTaskQueryDTO) *model.PageResult {
	sql := `select * from ts_task a where 1=1 `
	data := make([]entity.TsTask, 0)
	b := sbuilder.StructToBuilder(query, sql)
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m TsTaskService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.id as value, a.name as label from ts_task a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.id,a.name)", query.Label)
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.id", query.Selected))
	sql, values := b.Build()
	if len(query.Selected) != 0 {
		//sql += `order by a.id not in (` + strings.Join(query.Selected, ",") + `)`
	}
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}

func (m *TsTaskService) GetIdOrName(id string) any {
	data := new(vo.TsTaskVO)
	sql := `select * from ts_task where 1=1 `
	builder := sbuilder.Builder(sql)
	builder.Eq("id", id)
	builder.Or().Eq("name", id)
	sql, values := builder.Build()
	err := sgorm.DB.SelectSQL(data, sql, values...)
	if err != nil {
		return err
	}
	return data
}
